package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
)

/*
断点续传
seek可以随机的读取文件、写入文件操作
*/

func main() {
	// 一边复制一边记录总字节数
	srcFile := "E:\\AllCodes\\Base\\README.md"
	destFile := "E:\\AllCodes\\Base\\21io\\README.md"
	tempFile := "E:\\AllCodes\\Base\\21io\\temp.txt"
	file1, err := os.Open(srcFile)
	if err != nil {
		fmt.Println(err)
		return
	}
	file2, err := os.OpenFile(destFile, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	file3, err := os.OpenFile(tempFile, os.O_CREATE|os.O_RDWR, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file1.Close()
	defer file2.Close()
	defer file3.Close()

	// 1.读取临时文件中的数据
	file3.Seek(0, io.SeekStart)
	bs := make([]byte, 100, 100)
	n1, err := file3.Read(bs)
	countStr := string(bs[:n1])
	count, err := strconv.Atoi(countStr)
	fmt.Println(count)
	// 2. 设置偏移量
	file1.Seek(int64(count), io.SeekStart)
	file2.Seek(int64(count), io.SeekStart)

	buffer := make([]byte, 512, 512)
	total := 0
	// 3. 进行文件复制
	for {
		n, err := file1.Read(buffer)
		if err == io.EOF || n == 0 {
			fmt.Println("复制完毕")
			os.Remove(tempFile)
			break
		} else if err != nil {
			fmt.Println(err)
			return
		}
		file2.Write(buffer[:n])
		total += n

		//将复制的总量存储到临时文件中
		file3.Seek(0, io.SeekStart)
		file3.WriteString(strconv.Itoa(total))

	}

}
func main1() {
	file, err := os.OpenFile("E:\\AllCodes\\Base\\21io\\a.txt", os.O_RDWR, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()

	bs := []byte{0}
	file.Read(bs)
	fmt.Println(string(bs))

	file.Seek(3, 0)
	file.Read(bs)
	fmt.Println(string(bs))

	file.Seek(2, 0)
	file.Read(bs)
	fmt.Println(string(bs))

}
